package other

import (
	"go-gin-api/app/model"
	"go-gin-api/app/model/github"
	"go-gin-api/app/util"

	"github.com/gin-gonic/gin"
)

// AddGithubService 添加开源项目服务
type AddGithubService struct {
	ID        string `json:"id"`
	Name      string `json:"name"`
	CountName string `json:"count_name"`
	URL       string `json:"url"`
	Star      string `json:"star"`
	Desc      string `json:"desc"`
	Language  string `json:"language"`
	Status    string `json:"status"`
}

// AddGithub 添加开源项目
func (s *AddGithubService) AddGithub(c *gin.Context) *util.Response {
	g := github.Github{
		Name:     s.Name,
		Author:   s.CountName,
		URL:      s.URL,
		Star:     s.Star,
		Status:   s.Status,
		Language: s.Language,
		Desc:     s.Desc,
	}

	// 参数校验
	if err := s.valid(); err != nil {
		return err
	}
	// 创建操作
	if s.ID == "" {
		if err := model.DB.Create(&g).Error; err != nil {
			return &util.Response{
				Code:    4000,
				Message: "failed",
				Data:    "创建项目失败!",
			}
		}
	} else {
		// 更新操作
		if err := model.DB.Model(&github.Github{}).Where("ID=?", s.ID).Update(&g).Error; err != nil {
			return &util.Response{
				Code:    4000,
				Message: "failed",
				Data:    "更新项目失败!",
			}
		}
	}

	return &util.Response{
		Code:    200,
		Message: "success",
		Data:    g,
	}
}
func (s *AddGithubService) valid() *util.Response {
	if s.Name == "" {
		return &util.Response{
			Code:    4000,
			Message: "failed",
			Data:    "请输入开源项目名!",
		}
	}
	if s.CountName == "" {
		return &util.Response{
			Code:    4000,
			Message: "failed",
			Data:    "请输入开源项目账户名!",
		}
	}
	if s.URL == "" {
		return &util.Response{
			Code:    4000,
			Message: "failed",
			Data:    "请输入开源项目url!",
		}
	}
	// 创建操作才会校验重复性
	if s.ID == "" {
		count := 0
		model.DB.Model(&github.Github{}).Where("url=?", s.URL).Count(&count)
		if count > 0 {
			return &util.Response{
				Code:    4000,
				Message: "failed",
				Data:    "该记录已经存在!",
			}
		}
	}

	return nil
}
